package com.itheima.interceptor;


import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先拿到token
        String token = request.getHeader("token");
        System.out.println(token);
        if(StringUtils.isEmpty(token)){
            //如果token不存在的话
            System.out.println("allaalallalala");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //如果token存在的话 解析
        try{
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            // 向当前线程中保存了一个UserInfo
            UserThreadLocal.setUserInfo(new UserThreadLocal.UserInfo(id, username));
            // token是合法的
            // 放行
            return true;

        }catch (Exception e){
            //如果解析失败的话
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //以上如果解析没问题的话 就可以直接放行
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 页面渲染完成以后再执行
        // 就算controller执行的时候出现异常，这个方法也要执行
        log.info("afterCompletion:{}", request.getRequestURI());
        // 从当前线程中删除UserInfo
        UserThreadLocal.removeUserInfo();
    }

}
